
package com.apps.ubc.cc.controller;

/*
 * 
 * @author Brandon Wong 
 */
import com.apps.datastore.AccountInformationDatastore;
import com.apps.datastore.dao.AccountObject;
import com.apps.datastore.dao.ContactInformationObject.CARRIER;
import com.apps.utils.BCryptUtils;
import com.apps.utils.EmailUtils;
import com.apps.outgoing.AccountActivation;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.io.IOException;
import java.math.BigInteger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegisterFormController extends HttpServlet {

	AccountInformationDatastore d = new AccountInformationDatastore();
	private SecureRandom random = new SecureRandom();
	public final int length = 15;
	private String email;
	private String password;
	private String passwordAgain;
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp){
		try {
			resp.sendRedirect("/register.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		email = req.getParameter("username").toLowerCase();
		password = req.getParameter("password");
		passwordAgain = req.getParameter("confirmation");
		if(!EmailUtils.isValidEmail(email)){
			resp.sendRedirect("/debug.jsp?msg=invalid_email");
		}
		else if (password.equals(passwordAgain)) {
			String authKey = randomStringGenerator();
			if (this.signup(email, password, authKey)) {
				// send an email with the random String
				// and notify it's all good :)
				AccountActivation a = new AccountActivation();
				a.sendVerification(email,authKey);
				
				resp.sendRedirect("/debug.jsp?msg=activation_email_sent");
			} else {
				// DUPLICATE USERNAME!!
				resp.sendRedirect("/debug.jsp?msg=registration_dupe_username");
			}

		} else {
			//Passwords are not identical
			resp.sendRedirect("/debug.jsp?msg=registration_pw_not_identical");
		}

	}

	private String randomStringGenerator() {
		MessageDigest m;
		try {
			m = MessageDigest.getInstance("MD5");
			String randomString = nextSessionId();
			m.update(randomString.getBytes(), 0, randomString.length());
			return new BigInteger(1,m.digest()).toString(16);

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return "";
	}

	private boolean signup(String username, String password, String randomString) {

		String encryptedPassword = BCryptUtils.hashpw(password,
				BCryptUtils.gensalt());
		boolean result = false;

		if (!d.checkAccountExist(username)) {

			AccountObject obj = new AccountObject(username,
					encryptedPassword, false, randomString, 1, "",CARRIER.NULL);

			result = d.addAccount(obj);

		}
		return result;
	}

	public String nextSessionId() {
		return new BigInteger(130, random).toString(length);
	}

}
